<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="department" v-if="departmentCustomerProductAnalysis">部门</el-menu-item>
      <el-menu-item index="all" v-if="allCustomerProductAnalysis">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="130px" :rules="rules">
        <el-form-item label="日期：">
          <el-date-picker
            v-model="listQuery.orderTime"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户编号：">
          <el-input v-model="listQuery.customerNumber" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称：">
          <el-select
            clearable
            v-model="listQuery.customerName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading">
            <el-option
              v-for="item in customerList"
              :key="item.customerName"
              :label="item.customerName"
              :value="item.customerName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品类：">
          <el-cascader
            filterable
            @change="changeCategoryId"
            :options="categoryList" clearable v-model="listQuery.categoryId" :props="{emitPath:false,value:'categoryId',label:'categoryName'}"></el-cascader>
        </el-form-item>

        <el-form-item label="牌号：" >
          <el-select
            @change="changeGoodsSn"
            v-model="listQuery.goodsName"
            filterable
            placeholder="请选择/输入牌号"
            clearable>
            <el-option
              v-for="(item,index) in goodsList"
              :key="index"
              :label="item.brandName+'/'+item.goodsSn"
              :value="item.categoryId+'/'+item.brandId+'/'+item.goodsSn">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人：">
          <el-select v-model="listQuery.userId" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.realName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否成交：">
          <el-select v-model="listQuery.isOrder" placeholder="请选择" clearable>
            <el-option key="1" label="是" value="1"></el-option>
            <el-option key="0" label="否" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序字段：">
          <el-select v-model="listQuery.orderBy" placeholder="请选择" clearable @change="changeOrderBy">
            <el-option key="about_buy_num" label="预估月用量" value="about_buy_num"></el-option>
            <el-option key="ship_num" label="实际销量" value="ship_num"></el-option>
            <el-option key="avg_profit" label="平均吨毛利" value="avg_profit"></el-option>
            <el-option key="sale_profit" label="总毛利" value="sale_profit"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序类型：" v-if="listQuery.orderBy">
          <el-select v-model="listQuery.sort" placeholder="请选择" clearable >
            <el-option key="DESC" label="降序" value="DESC"></el-option>
            <el-option key="ASC" label="升序" value="ASC"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事业部：" v-if="listQuery.tab == 'all' || listQuery.tab=='department'">
          <el-select v-model="listQuery.divsionDeptId" filterable placeholder="请选择" clearable multiple>
            <el-option :value="item.divsionDeptId" :label="item.divsionDeptName" v-for="item in divisionList" :key="item.divsionDeptId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="list"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
          label="客户"
          align="center"
          min-width="250">
          <template slot-scope="scope">
            <div>
              {{scope.row.customerNumber}}
            </div>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="子客户"
          align="center"
          min-width="300">
          <template slot-scope="scope">
            <span v-for="(item,index) in scope.row.subCustomer">
              <span>{{scope.row.isShowCustomerName ? item.customerName : item.customerNumber}}</span><span v-if="index < scope.row.subCustomer.length-1">,</span>
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="负责人"
          align="center"
          min-width="100">
          <template slot-scope="scope">
              {{scope.row.userName}}
          </template>
        </el-table-column>

        <el-table-column
          class-name="cspantd"
          label="品名"
          align="center"
          min-width="180">
          <template slot-scope="scope">
            {{scope.row.goodsName}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="牌号"
          align="center"
          min-width="180">
          <template slot-scope="scope">
            {{scope.row.brandName}}/{{scope.row.goodsSn}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="是否成交"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            {{scope.row.isOrder == 1 ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="预估月用量"
          align="center"
          min-width="150">
          <template slot-scope="scope">
             {{scope.row.aboutBuyNum}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="实际销量"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            {{scope.row.shipNum}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="平均吨毛利"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            {{scope.row.avgProfit}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="总毛利"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            {{scope.row.saleProfit}}
          </template>
        </el-table-column>

      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import { getCustomerOption,getUserOption,} from '@/api/partner'
import { divisionDeptList,getBrandAndGoodsSn,getCategoryList,customerGoodsAnalysis } from '@/api/company';

import {formatDate} from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
const defaultListQuery={
  "tab": "my", //my-我的，department-部门，all-全部
  "orderTime": [], //日期
  "customerName": "", //客户名称
  "customerNumber": "", //客户编码
  "userId": "", //业务员ID
  "divsionDeptId": [], //事业部ID
  "categoryId": "", //品类ID
  "brandId": "", //厂家ID
  "goodsSn": "", //牌号
  "isOrder": "", //是否成交，0-否，1-是
  "orderBy": "", //排序字段：about_buy_num-预估月用量，ship_num-实际销量，avg_profit-平均吨毛利，sale_profit-总毛利
  "sort": "", //排序：DESC-降序，ASC-升序
  "pageNum": 1,
  "pageSize": 10,
  goodsName:''
};
export default {
  name: "customerProductAnalysis",
  data(){
    return{
      roles:store.getters.roles ? store.getters.roles : [],
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      list:[],
      count:0,
      loading:false,
      goodsList:[],
      customerList:[],
      userOptionList:[],
      divisionList:[],
      orderStateList:[],
      rules:{

      },
      categoryList:[]
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    departmentCustomerProductAnalysis() {
      if (this.roles.indexOf("departmentCustomerProductAnalysis") != -1) {
        return true
      } else {
        return false
      }
    },
    allCustomerProductAnalysis() {
      if (this.roles.indexOf("allCustomerProductAnalysis") != -1) {
        return true
      } else {
        return false
      }
    },

  },
  created() {
    let now = new Date();
    let nowMonth = now.getMonth(); //当前月
    let nowYear = now.getFullYear(); //当前年
    //本月的开始时间
    let monthStartDate = new Date(nowYear, nowMonth, 1);
    //本月的结束时间
    let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
    let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
    let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
    this.listQuery.orderTime = [startDate,endDate];
    this.getListData();
    this.getcategoryListFn();
    this.getUserOptionList()
    this.getDivisionDeptList()
  },
  filters: {
    formatTime(time) {
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd')
    },
  },
  methods:{
    changeOrderBy(){
        this.listQuery.sort = this.listQuery.orderBy ? this.listQuery.sort : ''

    },
    changeGoodsSn(){
      let i = this.goodsList.findIndex((el)=>{
        return el.categoryId+'/'+el.brandId+'/'+el.goodsSn == this.listQuery.goodsName
      })
      if(i!= -1){
        this.listQuery.goodsSn = this.goodsList[i]['goodsSn']
        this.listQuery.brandId = this.goodsList[i]['brandId']
        this.listQuery.goodsName = this.listQuery.categoryId+'/'+this.listQuery.brandId+'/'+this.listQuery.goodsSn
      }else{
        this.listQuery.goodsSn = ''
        this.listQuery.brandId = ''
        this.listQuery.goodsName = ''
      }
    },

    //获取品类列表
    getcategoryListFn(){
      getCategoryList().then((res)=>{
        this.categoryList = res.list
      })
    },

    //切换品类
    changeCategoryId(){
      this.listQuery.goodsSn = ''
      this.listQuery.brandId = ''
      this.listQuery.goodsName = ''
      this.getOrderGoodsList();
    },

    // 获取牌号列表
    getOrderGoodsList(){
      if(this.listQuery.categoryId){
        getBrandAndGoodsSn({
          categoryId:this.listQuery.categoryId
        }).then((res)=>{
          this.goodsList = res.list
        })
      }
    },


    /**
     * 切换选择状态
     */
    handleSelect(key, keyPath) {
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery.tab = key;
      let now = new Date();
      let nowMonth = now.getMonth(); //当前月
      let nowYear = now.getFullYear(); //当前年
      //本月的开始时间
      let monthStartDate = new Date(nowYear, nowMonth, 1);
      //本月的结束时间
      let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
      let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
      let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
      this.listQuery.orderTime = [startDate,endDate];
      this.handleSearchList();
    },


    //获取事业部列表
    getDivisionDeptList(){
      divisionDeptList().then((res)=>{
        this.divisionList = res
      })
    },

    //获取员工下拉选项
    getUserOptionList(){
      getUserOption().then((res)=>{
        this.userOptionList = res;
      })
    },
    //查询获取客户列表
    remoteMethod(query) {
      if(query && query!= ''){
        this.loading = true;
        getCustomerOption({keywords:query}).then(response => {
          this.customerList = response;
          this.loading = false;
        }).catch(()=>{
          this.loading = false;
        });
      }
    },
    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getListData();
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getListData();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getListData();
    },

    getListData(){
      this.loading = true;
      customerGoodsAnalysis(this.listQuery).then((res)=>{
        this.list = res.list;
        this.count = res.count;
        this.loading = false;
      }).catch(()=>{
        this.loading = false;
      })
    },

  },
}
</script>

<style scoped lang="scss">
.cspantd{
  padding:0 !important;
  .cell{
    padding:0 !important;
    .tdDiv{
      padding:5px 10px;
      min-height: 20px;
      line-height: 20px;
      box-sizing: content-box;
      text-align: center;
    }
  }
}
</style>
